
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.BusinessLogic.DomainService;
using Yozeev.BusinessLogic.Authorization;
using Yozeev.Common;
using Abp.Authorization.Users;

namespace Yozeev.BusinessLogic
{
	/// <summary>
	/// ScenicSpot应用层服务的接口实现方法  
	///</summary>
	[AbpAuthorize]
	public class ScenicSpotAppService : YozeevAppServiceBase, IScenicSpotAppService
    {
        private readonly IRepository<ScenicSpot, Guid> _entityRepository;

        private readonly IScenicSpotManager _entityManager;

        private readonly IQueryHelper _queryHelper;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public ScenicSpotAppService(
        IRepository<ScenicSpot, Guid> entityRepository
        ,IScenicSpotManager entityManager
            , IQueryHelper queryHelper
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
            _queryHelper = queryHelper;
        }


        /// <summary>
        /// 获取ScenicSpot的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ScenicSpotListDto>> GetPaged(GetScenicSpotsInput input)
        {
            var expression = _queryHelper.WhereExp<ScenicSpot>(input.queryData);
			if (AbpUserBase.AdminUserName != GetCurrentUser().UserName)
				expression = _queryHelper.SetWhereExp<ScenicSpot>(expression, GetViewTypeEnum<ScenicSpot>(), await GetBranchUser());
			var query = _entityRepository.GetAll().Where(expression);
			// TODO:根据传入的参数添加过滤条件
			List<ScenicSpot> list = new List<ScenicSpot>();
			var queryList = query.ToList();
			if (queryList != null && queryList.Count > 0)
				queryList.Where(m => m.ParentId == null).ToList().ForEach(t => {
					list.Add(t);
					CreateSubMenuListDtoNode(queryList, t, list);
				});
            //query = list.AsQueryable();
            var count = list.Count();
			list = list.AsQueryable().OrderBy(input.Sorting)
					.PageBy(input)
					.ToList();
			// var entityListDtos = ObjectMapper.Map<List<ScenicSpotListDto>>(entityList);
			var entityListDtos = list.MapTo<List<ScenicSpotListDto>>();

			return new PagedResultDto<ScenicSpotListDto>(count, entityListDtos);
		// var query = _entityRepository.GetAll();
		//// TODO:根据传入的参数添加过滤条件
		//var count = await query.CountAsync();

		//var entityList = await query
		//		.OrderBy(input.Sorting).AsNoTracking()
		//		.PageBy(input)
		//		.ToListAsync();

		//// var entityListDtos = ObjectMapper.Map<List<ScenicSpotListDto>>(entityList);
		//var entityListDtos =entityList.MapTo<List<ScenicSpotListDto>>();

		//return new PagedResultDto<ScenicSpotListDto>(count,entityListDtos);
	}

	
	private void CreateSubMenuListDtoNode(List<ScenicSpot> items, ScenicSpot item, List<ScenicSpot> scenicTrees)
	{
		List<ScenicSpot> sub = items.Where(m => m.ParentId == item.Id).ToList();
		if (sub != null && sub.Count > 0)
			sub.ForEach(t => {
				scenicTrees.Add(t);
				CreateSubMenuListDtoNode(items, t, scenicTrees);
			});

	}


	/// <summary>
	/// 通过指定id获取ScenicSpotListDto信息
	/// </summary>
		public async Task<ScenicSpotListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<ScenicSpotListDto>();
		}

		/// <summary>
		/// 获取编辑 ScenicSpot
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetScenicSpotForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetScenicSpotForEditOutput();
ScenicSpotEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<ScenicSpotEditDto>();

				//scenicSpotEditDto = ObjectMapper.Map<List<scenicSpotEditDto>>(entity);
			}
			else
			{
				editDto = new ScenicSpotEditDto();
			}

			output.ScenicSpot = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改ScenicSpot的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdateScenicSpotInput input)
		{

			if (input.ScenicSpot.Id.HasValue)
			{
				await Update(input.ScenicSpot);
			}
			else
			{
				await Create(input.ScenicSpot);
			}
		}


		/// <summary>
		/// 新增ScenicSpot
		/// </summary>
		protected virtual async Task<ScenicSpotEditDto> Create(ScenicSpotEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            // var entity = ObjectMapper.Map <ScenicSpot>(input);
            var entity=input.MapTo<ScenicSpot>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<ScenicSpotEditDto>();
		}

		/// <summary>
		/// 编辑ScenicSpot
		/// </summary>
		protected virtual async Task Update(ScenicSpotEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除ScenicSpot信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除ScenicSpot的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		/// <summary>
		/// 导出ScenicSpot为excel表,等待开发。
		/// </summary>
		/// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


